package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.MessageStatus;
import com.example.forum.common.enums.MessageReplyStatus;
import com.example.forum.common.enums.ResultCode;
import com.example.forum.common.enums.UserStatus;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hanzishuai
 * @date 2025/4/13 14:43
 * @Description 站内信接口
 */
@Tag(name = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {


    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @PostMapping("/send")
    @Operation(summary = "发送站内信")
    public AppResult send(HttpServletRequest request,
                          @Parameter(description = "接收者 Id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @Parameter(description = "发送内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 校验发信者状态
        if (user == null || user.getDeleteState() == UserStatus.IS_DELETE.getCode()) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        // 不能给自己发站内信
        if (user.getId().equals(receiveUserId)) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_SEND_TO_SELF);
        }

        // 校验用户禁言状态
        if (user.getId() == UserStatus.IS_BANNED.getCode()) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == UserStatus.IS_DELETE.getCode()) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_RECEIVE_ABNORMAL));
        }

        // 封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);

        // 调用 Service
        messageService.create(message);

        return AppResult.success("发送成功！");
    }


    @Operation(summary = "获取未读数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getsUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        Integer count = messageService.selectUnreadCount(user.getId());

        return AppResult.success(count);
    }


    @Operation(summary = "查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        List<Message> messages = messageService.selectByReceiveUserId(user.getId());

        return AppResult.success(messages);
    }


    @Operation(summary = "更新站内信为已读状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(description = "站内信 Id") @RequestParam("id") @NonNull Long id) {

        // 根据 Id 查询，站内信
        Message message = messageService.selectById(id);
        // 站内信是否存在
        if (message == null || message.getDeleteState() == MessageStatus.IS_DELETE.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }


        // 站内信接收者是否是自己
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (message.getPostUserId().equals(user.getId())) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        // 调用 Service
        messageService.updateStateById(id, MessageReplyStatus.IS_READ.getStatus());

        return AppResult.success();
    }


    /**
     * Created by hanzishuai on 2025/4/13
     *
     * @param repliedId 要回复的站内信 Id
     * @param content   要回复的站内信内容
     * @return com.example.forum.common.AppResult
     * @Description 回复站内信
     */
    @Operation(summary = "回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @Parameter(description = "要回复的站内信 Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @Parameter(description = "要回复的站内信内容") @RequestParam("content") @NonNull String content) {
        // 校验当前用户的登陆状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (user.getState() == UserStatus.IS_BANNED.getCode()) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验要回复站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == MessageStatus.IS_DELETE.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId().equals(existsMessage.getPostUserId())) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_REPLY_TO_SELF);
        }

        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content); // 内容

        // 调用 Service
        messageService.reply(repliedId, message);

        return AppResult.success();

    }

}




































